package cn.jsu.oj.dispatchServer.handle.handles;

import cn.jsu.oj.dispatchServer.dataStructure.MappingQueue;
import cn.jsu.oj.dispatchServer.handle.CommandPack;
import cn.jsu.oj.dispatchServer.init.ClientInitVector;
import cn.jsu.oj.dispatchServer.init.JudgeClient;
import cn.jsu.oj.dispatchServer.net.DispatchServerHandle;
import cn.jsu.oj.dispatchServer.parsing.HandleType;
import cn.jsu.oj.dispatchServer.pojo.ApplyTaskNumber;
import cn.jsu.oj.dispatchServer.pojo.CmdInformation;
import cn.jsu.oj.dispatchServer.pojo.QuantityResponse;
import cn.jsu.oj.dispatchServer.pojo.TaskInfo;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 24987
 */
@Slf4j
@HandleType(type = 21)
public class ApplyTaskHandle implements Handle {
    @Override
    public CommandPack<?> handle(CommandPack<?> pack) {
        ApplyTaskNumber applyTaskNumber = (ApplyTaskNumber) pack.getData();
        System.out.println();
        ClientInitVector clientInitVector = DispatchServerHandle.vectorMap.get(pack.getIpAndPort());
        JudgeClient init = (JudgeClient) clientInitVector.getInit();
        MappingQueue<TaskInfo> mappingQueue = init.getMappingQueue();
        Channel channel = clientInitVector.getChannel();

        //重构后的
        try {
            if (applyTaskNumber.getApplyNumber() > mappingQueue.size()) {
                    //发送任务调度任务数量相应包
                    channel.writeAndFlush(new ApplyTaskNumber((short) mappingQueue.size()).serialize());
            } else {
                    channel.writeAndFlush(new ApplyTaskNumber(applyTaskNumber.getApplyNumber()).serialize());
            }
        } catch (Exception e) {
            log.error(e.getLocalizedMessage() , e);
        } //
;

        short applyNumber = applyTaskNumber.getApplyNumber();
        for (int i = 0; i < applyNumber; i++) {
            try {
                if (mappingQueue.size() == 0) {
                    log.info("申请任务数:" + applyNumber + " 发送任务数:" + i);

                    //如果没有任务则返回空信息
//                    channel.write(new CmdInformation((byte) 4).serialize());
                    break;
                } else {
                    //返回任务
                    channel.write(mappingQueue.take().serialize());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //刷新缓冲区
        channel.flush();

        return null;
    }
}
